package org.example.multi_sys_consist.service;

import com.alibaba.fastjson.JSONObject;
import org.example.multi_sys_consist.constant.TransactionJobType;
import org.example.multi_sys_consist.mapper.ApplyMapper;
import org.example.multi_sys_consist.pojo.dto.ApplyApproveVo;
import org.example.multi_sys_consist.pojo.entity.ApplyEntity;
import org.example.multi_sys_consist.remote.FinanceLogSystemService;
import org.example.multi_sys_consist.remote.WorkflowService;
import org.example.multi_sys_consist.service.impl.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 拆分事务后的优化方案
 */
@Service
public class ApplyService2 {

    @Autowired
    private CurrentService currentService;
    @Autowired
    private ApplyMapper applyMapper;
    @Autowired
    private WorkflowService workflowService;
    @Autowired
    private LogService logService;
    @Autowired
    private TodoService todoService;
    @Autowired
    private TransactionJobService transactionJobService;

    @Transactional(rollbackFor = Exception.class)
    public void approve(Long id, ApplyApproveVo vo) {
        //---------第一步-----------
        //记录业务数据
        applyMapper.saveInfo(vo);
        //记录审核通过日志
        logService.addLog(currentService.currentUser().getAccount() + "审核通过了申请单" + id);
        //调用工作流服务
        ApplyEntity applyEntity = applyMapper.selectById(id);
        //删除本地所有待办人
        todoService.deleteByApplyId(id);

        //留下任务：更新待办
        JSONObject data = new JSONObject();
        data.put("workflowId", applyEntity.getBpmId());
        data.put("applyId", id);
        transactionJobService.create(TransactionJobType.UPDATE_TODO, data);

        //调用第三方接口：审核通过
        workflowService.approve(applyEntity.getBpmId());

    }
}
